package com.ruoyi.wechatapi.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.druid.util.StringUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信小程序授权接口
 */
@RestController
@RequestMapping("/api")
public class WechatController {
    /**
     * 微信小程序AppID
     */
    private final static String AppID = "wx16e599e5db71b8ba";
    /**
     * 微信小程序AppSecret
     */
    private final static String AppSecret = "d2905bb7d5b8a5d641f84af50580da97";


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    /**
     * 通过微信code进行登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/wxLogin")
    public AjaxResult loginByCode(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret, loginBody.getCode());
        String json = HttpUtils.sendGet(url, params);
        if(StringUtils.isEmpty(json)){
        	return AjaxResult.error("未获取到openid");
        }
        JSONObject jsonObject = JSONUtil.parseObj(json);
        String session_key = (String) jsonObject.get("session_key");
        String openId = (String) jsonObject.get("openid");
        if (StrUtil.isEmpty(openId)) {
            return AjaxResult.error("未获取到openid");
        }
        SysUser sysUser = userService.selectUserByOpenId(openId);
        if (ObjectUtil.isEmpty(sysUser)) {
            return AjaxResult.success("账号未与微信号绑定,请先使用进行个人账号登录并绑定微信号",0);
        }
        // 生成令牌
        String token = loginService.login(sysUser.getUserName(), loginBody.getPassword(), "weixinCode",
                loginBody.getUuid());
        SysUser user= SecurityUtils.getLoginUser().getUser();
        userService.updateSysUserLogin(user.getUserId());
        ajax.put(Constants.TOKEN, token);
        ajax.put("data", 1);
        return ajax;
    }


    /**
     * 账号与微信账号绑定
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/accountBinding")
    public AjaxResult accountBinding(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret, loginBody.getCode());
        String json = HttpUtils.sendGet(url, params);
        JSONObject jsonObject = JSONUtil.parseObj(json);
        String session_key = (String) jsonObject.get("session_key");
        String openId = (String) jsonObject.get("openid");
        if (StrUtil.isEmpty(openId)) {
            return AjaxResult.error("未获取到openid");
        }
        SysUser user1 = SecurityUtils.getLoginUser().getUser();
        SysUser sysUser1 = new SysUser();
        sysUser1.setOpenId(openId);
        sysUser1.setUserId(user1.getUserId());
        userService.updateUserStatus(sysUser1);
        return AjaxResult.success("账号绑定成功");
    }

    /**
     * 查询用户信息
     *
     * @return 结果
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser userData = userService.selectUserByUserName(user.getUserName());
        return AjaxResult.success(userData);
    }

}